function GetQueryString(name){
	var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if(r!=null)return  unescape(r[2]); return null;
}

function SubmitOrder(commodityList,presentList) {
	if(localStorage.userToken==undefined){
		console.log("请登陆");
		//alert(localStorage.userToken);
	}else{
var curOrderMsg = JSON.parse(localStorage.curOrderMsg);
console.log(curOrderMsg);
//alert(curOrderMsg);
var datastr = '{\"orderinfo\":{\"userId\":\"'
+localStorage.userId+'\",\"contactName\":\"'
+curOrderMsg.contactName+'\",\"contactPhone\":\"'
+curOrderMsg.contactPhone+'\",\"shippingMethod\":\"'
+(curOrderMsg.shippingMethod=='sendToHome'?'送货上门(推广期免费)':'自提点')+'\",\"orderAddress\":\"'
+curOrderMsg.orderAddress+'\",\"paymentMethod\":\"'+curOrderMsg.paymentMethod+'\",\"orderAdcode\":\"'
+localStorage.adcode+'\"},'
+'\"commodity\":['+commodityList+'],\"incidental\":['+presentList+']}';
console.log("生成订单传递的参数是:");
console.log(datastr);
var myNum=JSON.parse(localStorage.goodsList)[0].againOrderNumber;//获取再次下单的订单号
if(myNum){
	mui.ajax(API_HOST+'/client/orderinfo/againneworder',{
		data:{orderNumber:myNum,paymentMethod:curOrderMsg.paymentMethod},
		dataType:'json',//服务器返回json格式数据
		type:'post',//HTTP请求类型
		timeout:10000,//超时时间设置为10秒；
		headers:{'Content-Type':'application/json','usertoken':localStorage.userToken},	              
		success:function(data){
	 		//alert(1);
	 		console.log(commodityList);
	 		console.log(presentList);
			console.log(data.dataResultObj);
            if(curOrderMsg.paymentMethod=='Wechat'){
                if (typeof WeixinJSBridge == "undefined"){
                    if( document.addEventListener ){
                        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                    }else if (document.attachEvent){
                        document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                    }
                }else{
                    onBridgeReady(data);
                }
            }else{
                paySuccessCallBack();
			}
		},
		error:function(xhr,type,errorThrown){
			//异常处理；
			console.log(type);
		}
	});
}else{
		mui.ajax(API_HOST+'/client/orderinfo/generateorder',{
	 	data:datastr,
		dataType:'json',//服务器返回json格式数据
		type:'post',//HTTP请求类型
		timeout:10000,//超时时间设置为10秒；
		headers:{'Content-Type':'application/json','usertoken':localStorage.userToken},	              
		success:function(data){
	 		console.log(commodityList);
	 		console.log(presentList);
			console.log(data.dataResultObj);
			if(curOrderMsg.paymentMethod=='Wechat'){
                if (typeof WeixinJSBridge == "undefined"){
                    if( document.addEventListener ){
                        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                    }else if (document.attachEvent){
                        document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                    }
                }else{
                    onBridgeReady(data);
                }
			}else{
                paySuccessCallBack();
			}

		},
		error:function(xhr,type,errorThrown){
			//异常处理；
			console.log(type);
		}
	});
}





// function RSubmitOrder () {



// 	if(localStorage.usertoken==undefined){
// 		console.log("请登陆") 
// 	}


// else
// {


// var orderNumberdsds = $("#restnumber").val();
// $.ajax({
//   type:"post",    contentType: "application/json", //必须有
//   url: API_HOST+'/client/orderinfo/againneworder',
//   			 headers:{'userToken':localStorage.userToken},	  
  
 
//  data:"{'orderNumber':'"+orderNumberdsds+"'}",
 
// 			success:function(data){
// 				console.log(data.dataResultObj);



// if (typeof WeixinJSBridge == "undefined"){
//    if( document.addEventListener ){
//        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
//    }else if (document.attachEvent){
//        document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
//        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
//    }
// }else{
	
// 		 onBridgeReady(data);
	

   
// }

// 			},
// 			error:function(xhr,type,errorThrown){
// 				//异常处理；
// 				console.log(type);
// 			}
//          });






	
		
		
}
}



// function wechatrefund() {
// 	var a =$("#tko").val();
// 	var b  =$("#tkj").val();
// 	var c =$("#tkz").val();
// 	$.ajax({
//   type:"post",    contentType: "application/json", //必须有
//   url: API_HOST+'/api/wechat/pay/wechatrefund',
// data:"{'orderNumber':'"+a+"','refundFee':'"+b+"','paymentAmount':'"+c+"'}",
//   success: function(data){
//                  console.log(data)   
// $("#ordersts").val(data.htmlState)				 
//             } 
//          });
	
// }









function onBridgeReady(data){
   WeixinJSBridge.invoke(
       'getBrandWCPayRequest', {
           "appId":data.dataResultObj.appId,     //公众号名称，由商户传入     
           "timeStamp":data.dataResultObj.timeStamp,         //时间戳，自1970年以来的秒数     
           "nonceStr":data.dataResultObj.nonceStr, //随机串     
           "package":data.dataResultObj.prepayId,     
           "signType":"MD5",         //微信签名方式：     
           "paySign":data.dataResultObj.paySign //微信签名 
       },
       function(res){

           if(res.err_msg == "get_brand_wcpay_request:ok" ) {
               // $("#ordersts").val("支付成功")
               paySuccessCallBack();
           }
           else if (res.errMsg == "get_brand_wcpay_request:cancel") {
  	// $("#ordersts").val("已取消支付")		

		}    // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。 
       }




   ); 
}

function paySuccessCallBack(){
    var goodsList = JSON.parse(localStorage.goodsList);
    var maxAjaxCount = goodsList.length;
    var ajaxCount = 0;
    for(var i=0;i<goodsList.length;i++){
        var id = goodsList[i].commodityNumber;
        mui.ajax(API_HOST+'/client/detailed/deletebycommodity',{
            data:{commodityNumber:id},
            dataType:'json',//服务器返回json格式数据
            type:'post',//HTTP请求类型
            timeout:10000,//超时时间设置为10秒；
            headers:{'Content-Type':'application/json','usertoken':localStorage.userToken},
            success:function(data){
                ajaxCount++;
                if(ajaxCount==maxAjaxCount){
                    delete localStorage.goodsList;
                    delete localStorage.cache_checkedCommodityNumber;
                    window.location.href = 'myself_order_successfully.html';
                }
            },
            error:function(xhr,type,errorThrown){
                //异常处理；
                console.log(type);
            }
        });
    }
}